package cn.dsttl3.tupan.Ability.slice;

import cn.dsttl3.tupan.MyApp;
import cn.dsttl3.tupan.ResourceTable;
import cn.dsttl3.tupan.bean.baidu.FileMeta;
import cn.dsttl3.tupan.bean.baidu.FileMetas;
import cn.dsttl3.tupan.utils.aria2.Aria2;
import cn.dsttl3.tupan.utils.DataUtils;
import cn.dsttl3.tupan.utils.SizeUtil;
import cn.dsttl3.tupan.utils.baidu.BaiduDownloadLink;
import cn.dsttl3.tupan.utils.baidu.BaiduFileMeta;
import com.google.gson.Gson;
import com.prdownloader.*;
import com.prdownloader.Error;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.preferences.Preferences;
import ohos.miscservices.pasteboard.PasteData;
import ohos.miscservices.pasteboard.SystemPasteboard;
import java.util.ArrayList;
import java.util.List;

public class FileAbilitySlice extends AbilitySlice {
    String token;
    long fsid;
    String dlink;
    int downloadId = 0;
    FileMeta fileMeta;
    Button button;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_file);
        Preferences preferences = new DataUtils().getPreferences(getApplicationContext());
        token = preferences.getString("token",null);
        fsid = intent.getLongParam("fsid",0);
        Image fileIcon = (Image) findComponentById(ResourceTable.Id_file_icon);
        Text textName = (Text) findComponentById(ResourceTable.Id_file_name);
        Text size = (Text) findComponentById(ResourceTable.Id_file_size);
        Text textDlink = (Text) findComponentById(ResourceTable.Id_file_dlink);
        button = (Button) findComponentById(ResourceTable.Id_btn_aria2);
        ProgressBar progressBar = (ProgressBar) findComponentById(ResourceTable.Id_progressbar);
        PRDownloader.initialize(getApplicationContext());
        String path = getApplicationContext().getExternalFilesDir("download").getAbsolutePath();

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!new Aria2().test(getApplicationContext())){
                    getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            button.setText("Aria2连接失败");
                            button.setClickedListener(new Component.ClickedListener() {
                                @Override
                                public void onClick(Component component) {
                                    Intent aria2Intent = new Intent();
                                    Operation aria2Operation = new Intent.OperationBuilder()
                                            .withBundleName(MyApp.bundleName)
                                            .withAbilityName("cn.dsttl3.tupan.Ability.Aria2Ability")
                                            .build();
                                    aria2Intent.setOperation(aria2Operation);
                                    startAbility(aria2Intent);
                                    terminateAbility();
                                }
                            });
                        }
                    });
                } else {
                    getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            button.setText("使用Aria2下载");
                            button.setClickable(true);
                            button.setClickedListener(new Component.ClickedListener() {
                                @Override
                                public void onClick(Component component) {
                                    button.setClickable(false);
                                    button.setText("准备下载...");
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            List<String> list = new ArrayList<>();
                                            list.add(dlink);
                                            String s = new Aria2().download(list,getApplicationContext());
                                            getUITaskDispatcher().asyncDispatch(new Runnable() {
                                                @Override
                                                public void run() {
                                                    button.setText(s);
                                                    button.setClickable(false);
                                                }
                                            });
                                        }
                                    }).start();
                                }
                            });
                        }
                    });
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String fileMetaJSON = new BaiduFileMeta().get(token,fsid);
                FileMetas fileMetas = new Gson().fromJson(fileMetaJSON,FileMetas.class);
                fileMeta = fileMetas.getList().get(0);
                dlink = new BaiduDownloadLink().load(fileMeta.getDlink(),token);
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        switch ((int)fileMeta.getCategory()){
                            case 1:
                                fileIcon.setPixelMap(ResourceTable.Media_f1);
                                break;
                            case 2:
                                fileIcon.setPixelMap(ResourceTable.Media_f2);
                                break;
                            case 3:
                                fileIcon.setPixelMap(ResourceTable.Media_f3);
                                break;
                            case 4:
                                fileIcon.setPixelMap(ResourceTable.Media_f4);
                                break;
                            case 5:
                                fileIcon.setPixelMap(ResourceTable.Media_f5);
                                break;
                            case 6:
                                if(fileMeta.getFilename().endsWith(".rar")||fileMeta.getFilename().endsWith(".zip")||fileMeta.getFilename().endsWith(".7z")){
                                    fileIcon.setPixelMap(ResourceTable.Media_f9);
                                }else {
                                    fileIcon.setPixelMap(ResourceTable.Media_f6);
                                }
                                break;
                            case 7:
                                fileIcon.setPixelMap(ResourceTable.Media_f7);

                        }
                        textName.setText(fileMeta.getFilename());
                        size.setText(new SizeUtil().getPrintSize(fileMeta.getSize()));
                        textDlink.setText(dlink);
                        button.setVisibility(Component.VISIBLE);
                        progressBar.setVisibility(Component.VISIBLE);
                    }
                });
            }
        }).start();
        textDlink.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (textDlink.getMaxTextLines() > 15){
                    textDlink.setMaxTextLines(15);
                }else {
                    textDlink.setMaxTextLines(999);
                }
            }
        });
        textDlink.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                SystemPasteboard pasteboard = SystemPasteboard.getSystemPasteboard(getApplicationContext());
                if (pasteboard != null) {
                    pasteboard.setPasteData(PasteData.creatPlainTextData(dlink));
                    new ToastDialog(getContext()).setText("链接复制成功").show();
                }
            }
        });



        progressBar.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (downloadId == 0){
                    new ToastDialog(getContext()).setText("开始下载").show();
                    downloadId = PRDownloader.download(dlink,path,fileMeta.getFilename())
                            .setUserAgent("pan.baidu.com")
                            .build()
                            // 恢复下载
                            .setOnStartOrResumeListener(new OnStartOrResumeListener() {
                                @Override
                                public void onStartOrResume() {
                                    progressBar.setProgressHintText("正在下载");
                                }
                            })
                            //暂停下载
                            .setOnPauseListener(new OnPauseListener() {
                                @Override
                                public void onPause() {
                                    progressBar.setProgressHintText("恢复下载");
                                }
                            })
                            // 取消下载
                            .setOnCancelListener(new OnCancelListener() {
                                @Override
                                public void onCancel() {
                                    progressBar.setProgressHintText("已取消下载");
                                }
                            })
                            // 下载进程  currentBytes当前下载字节，totalBytes文件总字节。
                            .setOnProgressListener(new OnProgressListener() {
                                @Override
                                public void onProgress(Progress progress) {
                                    long currentBytes = progress.currentBytes;
                                    long totalBytes = progress.totalBytes;
                                    progressBar.setMaxValue((int)totalBytes);
                                    progressBar.setProgressValue((int)currentBytes);
                                    progressBar.setProgressHintText(new SizeUtil().getPrintSize(currentBytes) + "/" + new SizeUtil().getPrintSize(totalBytes));
                                }
                            })
                            .start(new OnDownloadListener() {
                                @Override
                                public void onDownloadComplete() {
                                    progressBar.setProgressHintText("下载完成");
                                }

                                @Override
                                public void onError(Error error) {
                                    progressBar.setProgressHintText("下载出错");
                                    downloadId = 0;
                                }
                            });
                    //QUEUED RUNNING 下载中
                }else if (PRDownloader.getStatus(downloadId).name().equals("QUEUED") || PRDownloader.getStatus(downloadId).name().equals("RUNNING")){
                    PRDownloader.pause(downloadId);
                    new ToastDialog(getContext()).setText("暂停下载").show();
                    // PAUSED  暂停
                }else if(PRDownloader.getStatus(downloadId).name().equals("PAUSED")){
                    PRDownloader.resume(downloadId);
                    new ToastDialog(getContext()).setText("恢复下载").show();
                    // 已完成下载
                }else if(progressBar.getProgressHintText().equals("下载完成")){
                    new ToastDialog(getContext()).setText(path).show();
                }
            }
        });

        progressBar.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                new ToastDialog(getContext()).setText("取消下载").show();
                PRDownloader.cancel(downloadId);
                downloadId = 0;
                progressBar.setProgressValue(0);
            }
        });

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
